package com.tchy.cloud.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jeecgframework.core.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 网易云信相关工具类
 * Created by zjy on 2017/1/17.
 */
public class NeteaseUtil {


    private static String appKey = "ac5c94a1a24506f85572f7e64d9b3c78";
    private static String appSecret = "62444483e5c7";
    private static String nonce =  "123456";

    /**
     * 创建云信
     * @param accid 32位之内 必须是唯一的
     * @param name 名称
     * @return
     */
    public static boolean createNeteaseUser(String accid,String name){

        try {
            HttpClient httpclient = new DefaultHttpClient();
            String url = "https://api.netease.im/nimserver/user/create.action";
            HttpPost httpPost = new HttpPost(url);

            String curTime = String.valueOf((new Date()).getTime() / 1000L);
            String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

            // 设置请求的header
            httpPost.addHeader("AppKey", appKey);
            httpPost.addHeader("Nonce", nonce);
            httpPost.addHeader("CurTime", curTime);
            httpPost.addHeader("CheckSum", checkSum);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            // 设置请求的参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("accid", accid));
            nvps.add(new BasicNameValuePair("name", name));
            nvps.add(new BasicNameValuePair("token", accid));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

            // 执行请求
            HttpResponse response = httpclient.execute(httpPost);

            // 打印执行结果
//            System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

            String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");

            System.out.println("responseEntity =" + responseEntity);
            //判断是否发送成功，发送成功返回true
            String code = JSON.parseObject(responseEntity).getString("code");

            if("200".equals(code)){
                return true;
            }else{
                System.out.println(responseEntity);
                return false;
            }

        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 获取视频频道列表
     * @param records 单页记录数，默认值为10
     * @param pnum 要取第几页，默认值为1
     * @param ofield 排序的域，支持的排序域为：ctime（默认）
     * @param sort 升序还是降序，1升序，0降序，默认为desc
     * @return
     */
    public static List<Map<String,Object>> getChannellist(Integer records,Integer pnum,String ofield,Integer sort){


        try {
            HttpClient httpclient = new DefaultHttpClient();
            String url = "https://vcloud.163.com/app/channellist";
            HttpPost httpPost = new HttpPost(url);

            String curTime = String.valueOf((new Date()).getTime() / 1000L);
            String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

            // 设置请求的header
            httpPost.addHeader("AppKey", appKey);
            httpPost.addHeader("Nonce", nonce);
            httpPost.addHeader("CurTime", curTime);
            httpPost.addHeader("CheckSum", checkSum);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

            // 设置请求的参数
            JSONObject nvps = new JSONObject();
            if(records != null){

                nvps.put("records", records);
            }
            if(pnum != null ){

                nvps.put("pnum", pnum);
            }

            if(StringUtil.isNotEmpty(ofield)){
                nvps.put("ofield", ofield);

            }
            if(sort != null){

                nvps.put("sort", sort);

            }
            System.out.println(nvps.toString());
            StringEntity params = new StringEntity(nvps.toString(), Consts.UTF_8);
            httpPost.setEntity(params);

            // 执行请求
            HttpResponse response = httpclient.execute(httpPost);

            // 打印执行结果
//            System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

            String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");

            System.out.println("responseEntity =" + responseEntity);
            //判断是否发送成功，发送成功返回true
            JSONObject code = JSON.parseObject(responseEntity);

            System.out.println(code.get("code"));

            //非200表示出错了
            if(200 != Integer.parseInt(String.valueOf(code.get("code"))) ){
                System.out.println("取频道列表信息失败,错误代码:" + code.get("code"));
                return null;
            }

            JSONObject retObj = (JSONObject) code.get("ret");

            return (List<Map<String, Object>>) retObj.get("list");

        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    /**
     * 根据vid获取视频文件
     * @param vid
     * @return
     */
    public static JSONObject getVideoByVid(Integer vid){
        try {
            HttpClient httpclient = new DefaultHttpClient();
            String url = "http://vcloud.163.com/app/vod/video/get?vid=584020";
            HttpPost httpPost = new HttpPost(url);

            String curTime = String.valueOf((new Date()).getTime() / 1000L);
            String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

            // 设置请求的header
            httpPost.addHeader("AppKey", appKey);
            httpPost.addHeader("Nonce", nonce);
            httpPost.addHeader("CurTime", curTime);
            httpPost.addHeader("CheckSum", checkSum);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

            // 设置请求的参数
            JSONObject nvps = new JSONObject();
            nvps.put("vid", vid);
            System.out.println(nvps.toString());
            StringEntity params = new StringEntity(nvps.toString(), Consts.UTF_8);
            httpPost.setEntity(params);
            // 执行请求
            HttpResponse response = httpclient.execute(httpPost);
            String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println("responseEntity =" + responseEntity);
            //判断是否发送成功，发送成功返回true
            JSONObject code = JSON.parseObject(responseEntity);
            System.out.println(code.get("code"));
            //非200表示出错了
            if(200 != Integer.parseInt(String.valueOf(code.get("code"))) ){
                System.out.println("取频道列表信息失败,错误代码:" + code.get("code"));
                return null;
            }
            JSONObject retObj = (JSONObject) code.get("ret");

            return retObj;

        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
//        NeteaseUtil.createNeteaseUser("asdsdsd123","asdsdsd123");
//        List<Map<String, Object>> param = NeteaseUtil.getChannellist(10,1,null,null);
//        System.out.println(param);

//        JSONObject jsonObject = JSONObject.parseObject("{\"code\":200,\"info\":{\"token\":\"holleSB4\",\"accid\":\"hollesb4\",\"name\":\"dsb4\"}}");
//        Integer code = Integer.parseInt(String.valueOf(jsonObject.get("code")));
//        if(code == 200){
//            System.out.println("SUCCESS");
//        }else{
//            System.out.println("FLAG");
//        }

        System.out.println(getVideoByVid(584020));
    }

}
